package com.ruifu.act.listener;

import com.fhzncloud.cloud.common.security.service.CloudUser;
import com.fhzncloud.cloud.common.security.util.SecurityUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component("multipleTaskCreateListener")
@Data
@Slf4j
public class MultipleTaskCreateListener implements TaskListener {

    @Autowired
    private TaskService taskService;

    // 流程实例ID -> 已经分配的人员列表 (如果一个流程实例里面有多个多任务实例的情况，需要重新定义map的key)
    private Map<String, List<String>> processInstanceTaskIdsMap = new HashMap<>();

    @Override
    public void notify(DelegateTask delegateTask) {
        CloudUser cloudUser = SecurityUtils.getUser();

        //TaskDefinitionKey 为当前正在执行的xml节点flow-id。每个ProcessInstanceId任务对应一个指定的flow-id
        //TenantId+key+id可以确定唯一的一个mapkey
        String processKeyId = cloudUser.getTenantId() + "-" + delegateTask.getTaskDefinitionKey() + "-" + delegateTask.getProcessInstanceId();

        if (!processInstanceTaskIdsMap.containsKey(processKeyId)) {
            processInstanceTaskIdsMap.put(processKeyId, new ArrayList<>());
        }
        processInstanceTaskIdsMap.get(processKeyId).add(delegateTask.getId());

        String[] allAssignees = delegateTask.getAssignee().split(",");
        // 最后一个多实例任务通知时，把所有任务进行指派
        if (processInstanceTaskIdsMap.get(processKeyId).size() == allAssignees.length) {
            List<String> taskIds = processInstanceTaskIdsMap.get(processKeyId);

            for (int index = 0; index < taskIds.size(); index++) {
                //重新分配assignee
                taskService.setAssignee(taskIds.get(index), null);
                taskService.claim(taskIds.get(index), allAssignees[index]);
            }

            //执行完毕之后，需要将当前的mapkey给remove掉。以免后面可能会进行驳回，导致重复出现多次执行节点
            processInstanceTaskIdsMap.remove(processKeyId);
        }
    }
}
